package abmb.pages;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import abmb.utils.MBPost;
import abmb.utils.PageParts;
import abmb.utils.Utilities;

/**
 * Servlet implementation class Index
 * @author Andrea Balboni
 * @version 1.0
 */
public class Index extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Index() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Utilities utils=new abmb.utils.Utilities();
		PageParts pp=new abmb.utils.PageParts();
		HttpSession session=request.getSession(true);
		boolean loggedin=utils.isLoggedIn(session);
		String searchkey=(String)request.getParameter("keyword");
		String tagsearchkey=(String)request.getParameter("tagkeyword");
		boolean skey=(searchkey==null?false:true);
		boolean tskey=(tagsearchkey==null?false:true);
		ArrayList<MBPost> postList=new ArrayList<MBPost>();
		response.setContentType("text/html");
		PrintWriter p= response.getWriter();
		p.println(pp.printHTMLHeader("AB-Microblog Home",loggedin));
		p.println(pp.printSidebar(loggedin));
		//p.println("<section>");
		int userID=-1;
		if(session.getAttribute("userID")!=null){
			 userID=Integer.parseInt((String)session.getAttribute("userID").toString());
		}
		if(!skey && !tskey && !loggedin){
			p.println(pp.printSearchForm());
		}
		else{
			if(!skey && !tskey && loggedin){
				postList=utils.getPostsByIDs(utils.findPostsByUsername((String)session.getAttribute("nickname")));
				}
			else if (skey || tskey){
				if(!loggedin)
					p.println(pp.printSearchForm());
				if(tskey){
					postList=utils.doSearchTag(tagsearchkey);
				}
				else{
					postList=utils.doSearch(searchkey);
				}
			}
			if(postList.isEmpty()){
				p.println("<section>");
				if(!skey && loggedin)
					p.println("No posts by user: "+(String)session.getAttribute("nickname"));
				else
					p.println("No post match search criteria: "+searchkey);
				p.println("</section>");
			}
			else{
			p.println(pp.printPosts(postList,userID));
			p.println();
			}
		}


	p.println(pp.printFooterSection());
	p.println(pp.printHTMLFooter());
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doGet(request,response);
}

}
